<script setup>
import PageContainer from '@/components/pageContainer.vue'
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/store'
import { updateAvatar } from '@/api/user'
import { ElMessage } from 'element-plus'
const {
  user: { user_pic }
} = useUserStore()
const imgUrl = ref(user_pic) //初始头像
const uploadRef = ref()
const onselectFile = (file) => {
  // 基于FileReader读取图片做预览
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
  //   imgUrl.value = URL.createObjectURL(file.raw)
}
const onupdateAvatar = async () => {
  await updateAvatar(imgUrl.value)
  ElMessage.success('头像上传成功')
  useUserStore().getUser()
}
onupdateAvatar()
</script>
<template>
  <page-container title="更换头像">
    <el-col :span="12">
      <el-upload
        ref="uploadRef"
        :show-file-list="false"
        class="avatar-uploader"
        :auto-upload="false"
        :on-change="onselectFile"
      >
        <img v-if="imgUrl" :src="imgUrl" />
        <el-icon
          v-else
          src="@/assets/avatar.jpg"
          class="el-icon-plus avatar-uploader-icon"
          ><Plus
        /></el-icon>
      </el-upload>
      <!-- 点击选择图片 可以调用  -->
      <el-button
        type="primary"
        plain
        :icon="Plus"
        size="large"
        @click="uploadRef.$el.querySelector('input').click()"
        >选择图片</el-button
      >
      <el-button
        type="success"
        plain
        :icon="Upload"
        size="large"
        @click="onupdateAvatar"
        >上传头像</el-button
      >
    </el-col>
  </page-container>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      margin-bottom: 2vh;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
